//发货单号弹框
import React from 'react';
import { Input, Modal } from 'antd';
import { ElNotification, ElSearchTable } from '@/components/el';
import requests from '@/utils/request';
import { ElFormProps } from '../../el/ElForm';
import { ElSearchTableColumns } from '../../el/ElSearchTable';
import './style.less';

interface Props {
  value?: any;
  placeholder: string;
  disabled: boolean;
  showColumn: string;
  onChange?: Function;
  onCancel?: Function;
  defaultSearchData?: any;
  filterData?: any;
}
interface State {
  isShowModal: boolean;
  value: any;
  expandTableLoadingMap: any;
  expandTableDataMap: { [key: string]: any };
  expandedRowKeys: any;
  docNo: string | number;
  [props: string]: any;
}

// 列表查询条件
const getTableSearchFormItems: ElFormProps = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
  items: [
    {
      title: '发货单号',
      name: 'docNo',
      span: 6,
      formOption: {
        type: '$input',
        props: {},
        events: {
          placeholder: '请输入发货单号'
        }
      }
    },
    {
      title: '销售单号',
      span: 6,
      name: 'relateDocNo',
      formOption: {
        type: '$input',
        props: {}
      }
    }
  ]
};

//展开列
const getExpandColumns = (): Array<ElSearchTableColumns> => [
  {
    title: '行号',
    width: 60,
    align: 'left',
    dataIndex: 'index',
    render: (text, record, index) => {
      return index + 1;
    }
  },
  {
    title: '商品编码',
    width: 180,
    align: 'center',
    dataIndex: 'itemCode'
  },
  {
    title: '商品名称',
    width: 180,
    align: 'center',
    dataIndex: 'itemName'
  },
  {
    title: '商品规格',
    width: 180,
    align: 'center',
    dataIndex: 'itemSpec'
  },
  {
    title: '条码',
    width: 180,
    align: 'center',
    dataIndex: 'barcode'
  },
  {
    title: '批次号',
    width: 180,
    align: 'center',
    dataIndex: 'lotNo'
  },
  {
    title: '订单数量',
    width: 100,
    align: 'center',
    dataIndex: 'saleQty'
  },
  {
    title: '配货数量',
    width: 100,
    align: 'center',
    dataIndex: 'allocQty'
  },
  {
    title: '配货已发数量',
    width: 100,
    align: 'center',
    dataIndex: 'shippedQty'
  },
  {
    title: '配货可发数量',
    width: 100,
    align: 'center',
    dataIndex: 'unShippedQty'
  },
  {
    title: '申请发货数量',
    width: 100,
    align: 'center',
    dataIndex: 'demandQty'
  },
  {
    title: '已拒收数量',
    width: 90,
    align: 'right',
    dataIndex: 'rejectQty'
  },
  {
    title: '备注',
    width: 180,
    align: 'center',
    dataIndex: 'remark'
  },
  {
    title: '实发数量',
    width: 100,
    align: 'center',
    dataIndex: 'qty'
  },
  {
    title: '实发含税金额',
    width: 100,
    align: 'center',
    dataIndex: 'amt'
  },
  {
    title: '仓库',
    width: 180,
    align: 'center',
    dataIndex: 'whId'
  },
  {
    title: '功能区',
    width: 150,
    align: 'center',
    dataIndex: 'deter2Name'
  },
  {
    title: '要求发货日期',
    width: 180,
    align: 'center',
    dataIndex: 'demanStartDate'
  },
  {
    title: '重量',
    width: 90,
    align: 'center',
    dataIndex: 'netWeight',
    render: (value, record) => `${value}${record?.weightUomName || ''}`
  },
  {
    title: '体积',
    width: 90,
    align: 'center',
    dataIndex: 'volume',
    render: (value, record) => `${value}${record?.volumeUomName || ''}`
  },
  {
    title: '签收数量',
    width: 100,
    align: 'center',
    dataIndex: 'confirmQty'
  },
  {
    title: '销售单号',
    width: 180,
    align: 'center',
    dataIndex: 'relateDocNo'
  },
  {
    title: '订单行号',
    width: 160,
    align: 'center',
    dataIndex: 'relateDocLineno'
  },
  {
    title: '是否需要安装',
    width: 100,
    align: 'center',
    dataIndex: 'needServiceFlag',
    render: (value) => (Number(value) ? '是' : '否')
  }
];

// 表单配置项
const getTableColumns = (): Array<ElSearchTableColumns> => [
  {
    title: '行号',
    dataIndex: 'lineNo',
    width: 45,
    render: (_: any, record: any, index: any) => index + 1
  },
  {
    title: '发货单号',
    width: 160,
    align: 'center',
    dataIndex: 'docNo'
  },
  {
    title: '销售单号',
    width: 130,
    align: 'center',
    dataIndex: 'relateDocNo'
  },
  {
    title: '订单类型',
    width: 80,
    align: 'center',
    dataIndex: 'relateDocTypeName'
  },
  {
    title: '发货单状态',
    width: 80,
    align: 'center',
    dataIndex: 'docStatusName'
  },
  {
    title: '销售公司',
    width: 130,
    align: 'center',
    dataIndex: 'ouName'
  },
  {
    title: '仓库',
    width: 180,
    align: 'left',
    dataIndex: 'whName'
  },
  {
    title: '功能区',
    width: 120,
    align: 'left',
    dataIndex: 'deter2Name'
  },
  {
    title: '客户编号',
    width: 120,
    align: 'center',
    dataIndex: 'custCode'
  },
  {
    title: '客户名称',
    width: 100,
    align: 'center',
    dataIndex: 'custName'
  },
  {
    title: '收货地址',
    width: 120,
    align: 'center',
    dataIndex: 'recvDetailaddr'
  },
  {
    title: '承运商',
    width: 130,
    align: 'center',
    dataIndex: 'carrier'
  },
  {
    title: '发货单日期',
    width: 130,
    align: 'center',
    dataIndex: 'docDate'
  },
  {
    title: '修改时间',
    width: 130,
    align: 'center',
    dataIndex: 'modifyTime'
  }
];

class DispatchBillSelection extends React.Component<Props, State> {
  constructor(props) {
    super(props);
    this.state = {
      isShowModal: false,
      value: null,
      expandTableLoadingMap: false,
      expandTableDataMap: {},
      expandedRowKeys: [],
      docNo: ''
    };
  }
  /**
   * react生命周期
   * 传入的props映射到state上面
   * @param props
   * @param state
   * @returns
   */
  static getDerivedStateFromProps(props, state) {
    const { value } = props;
    const { value: stateValue } = state;
    if (stateValue !== value) {
      return {
        value: props.value
      };
    }
    return null;
  }

  tableRef: any; //searchtable的ref
  tableDetailRef: any; //展开行的ref

  // 点击查询按钮控制弹框显隐
  handleSearch = () => {
    this.setState({ isShowModal: true });
  };
  /** 弹框取消 */
  onCancel = () => {
    this.setState({ isShowModal: false });
  };

  // 点击弹框确定
  onOk = () => {
    // 获取选中行
    const selectData = this.tableDetailRef.getSelectionData();
    const { docNo } = this.state;

    if (this.props.onChange) {
      this.props.onChange(
        { ...selectData, docNo },
        () => {
          this.onCancel();
        },
        this.tableRef
      );
    }
  };

  /**
   * 展开行点击
   * @param expanded
   * @param row
   */
  expand = async (expanded, row) => {
    if (expanded) {
      // 显示 loading
      this.setState({
        expandTableLoadingMap: true,
        expandedRowKeys: [row.id]
      });
      // 查看发货单详情接口-筛选了可退数量为0的数据
      const res = await requests(
        `/yst-order/order/salDo/findDetailByIdForReturn/${row.id}`,
        { method: 'get' }
      );
      if (res && res.success) {
        this.setState({
          docNo: row.docNo,
          value: row.docNo,
          expandTableDataMap: {
            [row.id]: res.data
          }
        });
      } else {
        ElNotification({
          type: 'error',
          message: res.message || res.data || '操作失败！'
        });
      }
      // 取消loading
      this.setState({ expandTableLoadingMap: false });
    } else {
      this.setState({ expandedRowKeys: [] });
    }
  };

  //展开行
  expandedRowRender = (record) => {
    return (
      <ElSearchTable
        tableId='oms_order_dispachBill_modal_detatil'
        rowKey='id'
        bordered
        loading={this.state.expandTableLoadingMap}
        onRef={(ref) => {
          this.tableDetailRef = ref;
        }}
        rowSelectionConfig={{
          type: 'checkbox',
          fixed: false,
          disabledRowIds: []
        }}
        scroll={{ x: 'min-content', y: 550 }}
        mode={{
          // 精简模式,是否隐藏搜索表格的某一块元素
          proxy: false, // 筛选器
          search: false, // SearchForm
          action: false, // actionButtons
          pagination: false, // 分页
          descriptions: false // descriptions
        }}
        dataSource={this.state.expandTableDataMap[record.id]}
        columns={getExpandColumns()}
      />
    );
  };

  /**
   * 查询列表接口
   * @param data
   */
  search = (data) => {
    return requests(`/yst-order/order/salDo/search`, {
      method: 'post',
      query: data
    });
  };

  render() {
    const { isShowModal, value, expandedRowKeys } = this.state;

    return (
      <div className='orgTreeStyle'>
        <Input.Search
          readOnly
          disabled={this.props.disabled}
          placeholder={this.props.placeholder}
          value={value}
          allowClear
          // onChange={this.handleChange}
          onSearch={this.handleSearch}
        />
        {isShowModal && (
          <Modal
            title='选择发货单'
            visible={isShowModal}
            width={1100}
            onOk={this.onOk}
            zIndex={1009}
            onCancel={this.onCancel}
          >
            <ElSearchTable
              tableId='oms_order_dispachBill_modal_index'
              rowKey='id'
              bordered
              rowSelectionConfig={null}
              defaultSearchData={this.props.defaultSearchData}
              expandable={{
                expandedRowRender: this.expandedRowRender,
                onExpand: this.expand,
                expandedRowKeys
              }}
              onRef={(ref) => {
                this.tableRef = ref;
              }}
              scroll={{ x: 'min-content', y: 'calc(100vh - 450px)' }}
              mode={{
                // 精简模式,是否隐藏搜索表格的某一块元素
                proxy: true, // 筛选器
                search: true, // SearchForm
                action: true, // actionButtons
                pagination: true, // 分页
                descriptions: false // descriptions
              }}
              searchFormProps={getTableSearchFormItems}
              tableProxy={{
                request: async (paramData) => {
                  return this.search({
                    ...paramData,
                    ...this.props.filterData,
                    orders: [
                      {
                        asc: false,
                        column: 'createTime'
                      }
                    ]
                  });
                },
                props: {
                  success: 'success',
                  result: 'data.records',
                  total: 'data.total'
                },
                autoLoad: true
              }}
              columns={getTableColumns()}
            />
          </Modal>
        )}
      </div>
    );
  }
}
export default DispatchBillSelection;
